#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   main.py
@Time    :   2024-03-11 02:27:53
@Author  :   chakcy
@Email   :   947105045@qq.com
@description   :   主函数
'''

from task import tiktok
from rpa_tool import init_chrome_driver
from common import SocketServer, AsyncSocketServer

import json
import sys
import threading
import asyncio

# 执行任务
def run_task(json_string) -> str:
    params:dict = json.loads(json_string)
    # 获取参数
    task_name = params.get('task_name', '')
    args = params.get('args', None)
    """
    task: 任务名称
    args: 参数
    """
    functions = {
        "tiktok": tiktok,
        "init_chrome_driver": init_chrome_driver
    }
    # 使用 get 方法从 functions 字典中获取函数，如果找不到则返回默认函数  
    func = functions.get(task_name, lambda args: {"task_name": task_name, "msg": "Task not found"})
    # 调用函数并传入参数
    result = func(args) if args is not None else func()
    return json.dumps({"task_name": task_name, "result": result})

# def run_server_in_thread(server, run_task_func):  
#     server.start(run_task_func) 

async def main():
    socketServer = AsyncSocketServer('127.0.0.1', 8888)
    await socketServer.start(run_task)
    await socketServer.close()

def run_asyncio_loop(loop):
    asyncio.set_event_loop(loop)  
    try:  
        loop.run_until_complete(main())  
    finally:  
        loop.close()  

if __name__ == '__main__':
    try:
    # 同步版本
    #     # 执行任务
    #     socketServer = SocketServer('127.0.0.1', 8888)
    #     server_thread = threading.Thread(target=run_server_in_thread, args=(socketServer, run_task))  
    #     server_thread.start() 
    #     while True:
    #         line = sys.stdin.readline()
    #         if line.strip() == 'shutdown':  
    #             print('Received shutdown signal, closing server...')  
    #             # 停止 SocketServer，并等待线程结束  
    #             socketServer.close()  # 假设您有一个 stop 方法来停止服务器  
    #             server_thread.join()  # 等待线程结束  
    #             break  
    
    # except KeyboardInterrupt:
    #     print('Server is shutting down...')  
    #     # 停止 SocketServer，并等待线程结束  
    #     socketServer.close()  
    #     server_thread.join()
        
    # 异步版本
        new_loop = asyncio.new_event_loop()
        server_thread = threading.Thread(target=run_asyncio_loop, args=(new_loop,))
        # server_thread = threading.Thread(asyncio.run(main()))
        server_thread.start()
        while True:
            line = sys.stdin.readline()
            if line.strip() == 'shutdown':  
                print('Received shutdown signal, closing server...')  
                new_loop.call_soon_threadsafe(new_loop.stop)
                server_thread.join()  # 等待线程结束  
                break 

    except KeyboardInterrupt:
        print('Server is shutting down...')  
        # 停止 SocketServer，并等待线程结束  
        new_loop.call_soon_threadsafe(new_loop.stop)
        server_thread.join()

    except Exception as e:
        print(e)
        import logging
        import os
        import datetime

        __dirname = os.path.dirname(os.path.abspath(__file__))
        if not os.path.exists(os.path.join(__dirname, r'log')):
            os.makedirs(os.path.join(__dirname, r'log'))

        datetime_str = datetime.datetime.now().strftime('%Y%m%d')

        logging.basicConfig(
            filename=os.path.join(__dirname, f'log/{datetime_str}.log'),
            level=logging.ERROR
        )
        logging.error(str(e))
        print("An error occurred, please check the error.log for more details.")
